﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommonFoundation.DataModel;
using System.IO;
using CommonFoundation.DataSource;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.ObjectModel;

namespace WHULive
{
    public class LessonAdmin
    {
        public LessonAdmin()
        {
            this.UpdateAllLessons();
        }

        private void UpdateAllLessons()
        {
            if (BindingSource.GetInstance().AllLessons.Count == 0)
            {
                this.ReadInLessons();
            }
        }

        private void ReadInLessons()
        {
            using (Stream input = File.OpenRead(FilePath.GetInstance().LessonsDataPath))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();

                BindingSource.GetInstance().AllLessons = (List<Lesson>) binaryFormatter.Deserialize(input);
            }
        }

        public ObservableCollection<Lesson> Search(string value)
        {
            ObservableCollection<Lesson> result = new ObservableCollection<Lesson>();

            foreach (Lesson lesson in BindingSource.GetInstance().AllLessons)
            {
                if (lesson.TeacherName.Contains(value) || lesson.LessonName.Contains(value))
                {
                    result.Add(lesson);
                }
            }

            return result;
        }
    }
}
